package com.linkage.rsearch.api;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.linkage.richers.log.Log;
import com.linkage.richers.util.DateUtil;
import com.linkage.richers.util.DownloadUtil;

public class SearchApi {
    private static final String APPID = "A6F2EA9A9AD60CAC48C0A58B71780206130E995B";
    private static final int MAXCOUNT = 200;

    public static List<SearchResult> search(String[] keywords) {
        List<SearchResult> rv = new LinkedList<SearchResult>();
        Set<String> kws = new HashSet<String>();
        for (String kw : keywords) {
            if (kw != null && kw.trim().length() > 0) {
                kws.add(kw);
            }
        }
        for (String keyword : kws) {
            int offset = 1;
            int totalCount = 0;

            if (keyword != null && keyword.trim().length() > 0) {
                try {
                    boolean over = false;
                    while (!over) {

                        StringBuffer sb = new StringBuffer(
                                "http://api.search.live.net/xml.aspx?");
                        sb.append("Appid=").append(APPID);
                        sb.append("&Query=").append(
                                urlEncode("\"" + keyword + "\""));
                        sb.append("&Sources=News");
                        // sb.append("&Options=EnableHighlighting");
                        sb.append("&News.Count=15");
                        sb.append("&News.Offset=").append(offset);
                        // sb.append("&News.SortBy=Date");

                        Document doc = DownloadUtil.downloadXML(sb.toString(),
                                "UTF-8");
                        if (doc == null) {
                            over = true;
                        } else {
                            if (totalCount == 0) {
                                NodeList nlCount = doc
                                        .getElementsByTagName("news:Total");
                                if (nlCount != null && nlCount.getLength() > 0) {
                                    totalCount = new Integer(
                                            ((Element) nlCount.item(0))
                                                    .getTextContent());
                                }
                            }
                            if (totalCount == 0) {
                                over = true;
                            } else {
                                if (totalCount > MAXCOUNT) {
                                    totalCount = MAXCOUNT;
                                }
                                NodeList nlNews = doc
                                        .getElementsByTagName("news:NewsResult");
                                int len = nlNews.getLength();
                                if (len > 0) {

                                    offset += len;
                                    for (int i = 0; i < len; i++) {
                                        Element onePiece = (Element) nlNews
                                                .item(i);
                                        parseSearchResult(onePiece, rv);

                                    }
                                    Log.debug("本次搜索结果：" + (offset - len) + "-"
                                            + offset + "/" + totalCount
                                            + ",关键字：" + keyword);
                                    if (offset >= totalCount) {
                                        over = true;
                                    }
                                } else {
                                    over = true;
                                }
                            }
                        }

                        // 每次调用搜索间隔一段时间以免和谐
                        // if (!over)
                        // Thread.sleep(1000);

                    }
                } catch (Exception e) {
                    Log.error(e);
                }

            }
        }
        return rv;
    }

    public static void main(String[] args) {
        List<SearchResult> rv = SearchApi.search(new String[] { "尖峰集团" });
        System.out.println(rv);
    }

    private static void parseSearchResult(Element onePiece,
            List<SearchResult> rv) {

        NodeList titles = onePiece.getElementsByTagName("news:Title");
        int len = titles.getLength();
        for (int i = 0; i < len; i++) {
            Element title = (Element) titles.item(i);
            SearchResult sr = new SearchResult();
            sr.setTitle(title.getTextContent());
            Element url = (Element) title.getNextSibling();
            sr.setUrl(url.getTextContent());
            Element source = (Element) url.getNextSibling();
            sr.setSource(source.getTextContent());
            Element snippet = (Element) source.getNextSibling();
            sr.setSnippet(snippet.getTextContent());
            Element time = (Element) snippet.getNextSibling();
            sr.setNewsTime(DateUtil.parseString(
                    time.getTextContent().replace('T', ' ').replace("Z", ""),
                    "yyyy-MM-dd HH:mm:ss"));
            rv.add(sr);
        }

    }

    private static String urlEncode(String src) {
        try {
            return URLEncoder.encode(src, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            Log.error(e);
        }
        return src;

    }
}
